﻿using System.Collections.Concurrent;

namespace YunQue.Core.Common.Extensions
{
    /// <summary>
    /// 枚举扩展
    /// </summary>
    public static class EnumsExtensions
    {
        private static readonly ConcurrentDictionary<string, Attribute> _enumAttributeDict = new ConcurrentDictionary<string, Attribute>();

        /// <summary>
        /// 获取枚举的特性信息
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static TAttribute GetAttributeInfo<TAttribute>(this Enum value) where TAttribute : Attribute
        {
            var type = value.GetType();
            var name = Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }
            var field = type.GetField(name);
            if (field == null)
            {
                return null;
            }
            return _enumAttributeDict.GetOrAdd($"Enum_{type.FullName}_{name}", (key) =>
            {
                var attr = Attribute.GetCustomAttribute(field, typeof(TAttribute)) as TAttribute;
                return attr;
            }) as TAttribute;
        }
        /// <summary>
        /// 获取所有的枚举值为Dictionary
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Dictionary<string, int> GetEnumDictionary(this Enum value)
        {
            var type = value.GetType();
            var names = Enum.GetNames(type);
            var values = Enum.GetValues(type);
            var dict = new Dictionary<string, int>();
            for (int i = 0; i < names.Length; i++)
            {
                dict.Add(names[i], (int)values.GetValue(i));
            }
            return dict;
        }
    }
}
